﻿using Inaction.Core;
using Inaction.Host;
using Inaction.Mapping;
using Inaction.ServiceProxy;
using System;
using System.Runtime.Remoting;

namespace Inaction.Service.Client.Proxy
{
    public class RemotingProxy : IProxy
    {
        private  Inaction.Host.IHost host = null;

        #region 构造
        public RemotingProxy()
        {
            RemotingConfiguration.RegisterActivatedClientType(typeof(IHost), AppConfig.Instance.ServerUrl);
            host = (IHost)Activator.GetObject(typeof(IHost), AppConfig.Instance.ServerUrl);
        }
        #endregion

        #region IProxy 成员
        public void Login()
        {
            var response = host.Login(new Request(new RequestData()));
            var responseData = response.GetObject<Inaction.ServiceProxy.ResponseData>();
            if (responseData.Exception != null)
            {
                throw responseData.Exception;
            }
            Inaction.Security.Principal.Instance = responseData.Data as Security.Principal;
        }
        public object Query(Type entityType, SqlStatement sql)
        {
            var response = host.Query(new Request(
                new RequestData(sql)
                {
                    Assembly = entityType.Assembly.GetName().Name,
                    FullName = entityType.FullName
                }));
            var data = response.GetObject<ResponseData>();
            if (data.Exception != null)
                throw data.Exception;
            return data.Data;
        }
        public object Save(ISavable obj)
        {
            var response = host.Save(new Request(new RequestData(obj)));
            var data = response.GetObject<ResponseData>();
            if (data.Exception != null)
                throw data.Exception;
            return data.Data;
        }
        public object Excute(SqlCommand command)
        {
            var response = host.Excute(new Request(new RequestData(command)));
            var data = response.GetObject<ResponseData>();
            if (data.Exception != null)
                throw data.Exception;
            return data.Data;
        }
        public object Invoke(RemotingMethod method)
        {
            var response = host.Invoke(new Request(new RequestData(method)));
            var data = response.GetObject<ResponseData>();
            if (data.Exception != null)
                throw data.Exception;
            return data.Data;
        }
        #endregion
    }
}